package br.com.esporte.view.site.component.listaTime;

import org.apache.wicket.behavior.AttributeAppender;
import org.apache.wicket.markup.html.WebMarkupContainer;
import org.apache.wicket.markup.html.list.ListItem;
import org.apache.wicket.markup.html.list.ListView;
import org.apache.wicket.model.Model;

import br.com.esporte.exception.ViewException;
import br.com.esporte.model.Jogador;
import br.com.esporte.model.Time;
import br.com.esporte.view.infra.component.ComponenteGenerico;
import br.com.esporte.view.infra.html.HtmlParam;
import br.com.esporte.view.site.component.listaTime.item.ItemTime;

/**
 * 
 * @author Milton Domingues
 *
 */
public class TimeComponent extends ComponenteGenerico {

	private static final long serialVersionUID = 1L;

	private static final String ITENS_TIME_ID = "itensTime";
	private static final String TIME_ID = "time";

	public static final String COLOR_YELLOW = "yellow";
	public static final String COLOR_BLUE = "blue";
	public static final String COLOR_RED = "red";

	private Time time;
	private String color;

	public TimeComponent(String id, Time time, String color) {
		super(id);
		setTime(time);
		setColor(color);
		validarView();
		carregarView();
		montarComponente();
	}

	private ListView<Jogador> criarItensTime(Time time){
		ListView<Jogador> itens = new ListView<Jogador>(ITENS_TIME_ID, time.getJogadores()) {

			private static final long serialVersionUID = 7639912465018533794L;

			@Override
			protected void populateItem(ListItem<Jogador> item) {
				Jogador jogador = item.getModelObject();
				ItemTime time = new ItemTime("item", jogador);
				time.setOutputMarkupId(true);
				item.add(time);
			}
		};
		itens.setOutputMarkupId(true);
		return itens;
	}

	private WebMarkupContainer criarTime(){
		WebMarkupContainer time = new WebMarkupContainer(TIME_ID);
		time.setOutputMarkupId(true);
		time.add(new AttributeAppender(HtmlParam.STYLE, new Model<String>(getStyleColor()), " "));
		return time;
	}

	public String getColor() {
		return color;
	}

	private String getStyleColor(){
		StringBuilder style = new StringBuilder();
		style.append("color:");
		style.append(getColor());
		return style.toString();
	}

	public Time getTime() {
		return time;
	}

	@Override
	public void montarComponente() {
		WebMarkupContainer time = criarTime();
		time.add(criarItensTime(getTime()));
		add(time);
	}

	public void setColor(String color) {
		this.color = color;
	}

	public void setTime(Time time) {
		this.time = time;
	}

	@Override
	public void validarView() {
		if(getTime() == null){
			throw new ViewException("Nenhum Time registrado.");
		}

		if((getTime().getJogadores() == null) || (getTime().getJogadores().size() == 0)){
			throw new ViewException("Nenhum Jogador registrado.");
		}
	}
}
